package com.tungse.juc.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Tungse
 * 自旋锁
 */
public class SpinLock_Demo {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public static void main(String[] args) throws InterruptedException {
        SpinLock_Demo spinLockDemo = new SpinLock_Demo();

        new Thread(()->{
            spinLockDemo.myLock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                spinLockDemo.myUnLock();
            }
        },"T1").start();

        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            spinLockDemo.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                spinLockDemo.myUnLock();
            }
        },"T2").start();

    }

    //加锁
    public void myLock() {
        Thread currentThread = Thread.currentThread();
        System.out.println(currentThread.getName() + "  加锁");
        //自旋锁
        while(!atomicReference.compareAndSet(null, currentThread)){

        }
        System.out.println(currentThread.getName() + "  加锁成功");
    }


    //解锁
    public void myUnLock() {
        Thread currentThread = Thread.currentThread();
        System.out.println(currentThread.getName() + "  解锁");
        atomicReference.compareAndSet(currentThread, null);
    }
}
